﻿using System.Web.Http;
using System;
using Models.Responses;
using Models.Requests;
using System.Collections.Generic;
using System.Data.SqlClient;
using DataAccess;
using Models.Models;
using System.Data;
using WebApi.Classes;

namespace WebApi.Controllers
{
    public class InvoiceController : ApiController
    {
        [HttpPost]
        public InvoiceListResponse GetUnInvoicedList(InvoiceListRequest request)
        {
            InvoiceListResponse response = new InvoiceListResponse() { InvoiceList = new InvoiceList() { List = new List<Invoice>() } };

            try
            {
                List<SqlParameter> parameters = new List<SqlParameter>();
                parameters.Add(new SqlParameter("biUserID", request.User.UserID));

                if (request.User.StoreID != request.User.ppjStoreID)
                {
                    parameters.Add(new SqlParameter("biStoreID", request.User.StoreID));
                }

                parameters.Add(new SqlParameter("iPageIndex", request.PageIndex));
                parameters.Add(new SqlParameter("iPageSize", request.PageSize));
                parameters.Add(new SqlParameter("szSortColumn", request.SortColumn));
                parameters.Add(new SqlParameter("szSortDirection", request.SortDirection));
                parameters.Add(new SqlParameter("bHideRevoked", request.HideRevoked));
                parameters.Add(new SqlParameter("biResultCount", 0) { Direction = ParameterDirection.Output });

                Statics.AddDebugParameters(parameters);

                var result = new DataSource().ExecuteDataSet("svc.uspGetUnInvoicedList", parameters);

                Statics.FetchDebugParameters((BaseResponse)response, result);

                if (result.DataSet != null && result.DataSet.Tables.Count > 0)
                {
                    foreach (DataRow row in result.DataSet.Tables[0].Rows)
                    {
                        response.InvoiceList.List.Add(new Invoice()
                        {
                            BillingPeriodName = row["BillingPeriodName"].ToString(),
                            BillingRate = Convert.ToDecimal(row["BillingRate"]),
                            BillingTypeName = row["BillingTypeName"].ToString(),
                            BillingUnit = Convert.ToInt64(row["BillingUnit"]),
                            DomainName = row["DomainName"].ToString(),
                            OrderSubmitFlag = Convert.ToBoolean(row["OrderSubmitFlag"]),
                            PopUpFlag = Convert.ToBoolean(row["PopUpFlag"]),
                            PopUpOrderTotal = Convert.ToDecimal(row["PopUpOrderTotal"]),
                            SessionDate = Convert.ToDateTime(row["SessionDate"]),
                            StoreName = row["StoreName"].ToString(),
                            SubmitOrderTotal = Convert.ToDecimal(row["SubmitOrderTotal"]),
                            BSettError = Convert.ToBoolean(row["bBSettError"])                            
                        });
                    }

                    response.InvoiceList.ResultCount = Convert.ToInt64(result.Parameters["biResultCount"].Value);
                }

                response.InvoiceList.PageIndex = request.PageIndex;
                response.InvoiceList.PageSize = request.PageSize;
                response.InvoiceList.SortColumn = request.SortColumn;
                response.InvoiceList.SortDirection = request.SortDirection;

                Statics.FetchDebugParameters((BaseResponse)response, result);
            }
            catch (Exception ex)
            {
                response.Exception = ex;
            }

            return response;
        }

        [HttpPost]
        public InvoiceResponse GetInvoice(InvoiceRequest request)
        {
            InvoiceResponse response = new InvoiceResponse() { Invoice = new Invoice() { ID = request.Invoice.ID }};

            try
            {
                List<SqlParameter> parameters = new List<SqlParameter>();
                parameters.Add(new SqlParameter("biUserID", request.UserID));
                parameters.Add(new SqlParameter("biBillingID", request.Invoice.ID));

                Statics.AddDebugParameters(parameters);

                var result = new DataSource().ExecuteDataSet("svc.uspGetInvoiceForPRN", parameters);

                Statics.FetchDebugParameters((BaseResponse)response, result);

                if (result.DataSet != null && result.DataSet.Tables.Count > 0)
                {
                    var row = result.DataSet.Tables[0].Rows[0];

                    response.Invoice.BillingDate = Convert.ToDateTime(row["BillingDate"]);
                    response.Invoice.StoreName = row["StoreName"].ToString();
                    response.Invoice.DomainName = row["DomainName"].ToString();
                    response.Invoice.BillingPeriodName = row["BillingPeriodName"].ToString();
                    response.Invoice.From = Convert.ToDateTime(row["DateFrom"]);
                    response.Invoice.To = Convert.ToDateTime(row["DateTo"]);
                    response.Invoice.BillingTypeName = row["BillingTypeName"].ToString();
                    response.Invoice.BillingRate = Convert.ToDecimal(row["BillingRate"]);
                    response.Invoice.Total = Convert.ToDecimal(row["InvTotal"]);
                    response.Invoice.NameOfUnit = row["NameOfUnit"].ToString();
                    response.Invoice.NumberOfUnits = Convert.ToDecimal(row["NumberOfUnits"]);
                }

                Statics.FetchDebugParameters((BaseResponse)response, result);
            }
            catch (Exception ex)
            {
                response.Exception = ex;
            }

            return response;
        }

        [HttpPost]
        public InvoiceListResponse GetInvoicedList(InvoiceListRequest request)
        {
            InvoiceListResponse response = new InvoiceListResponse() { InvoiceList = new InvoiceList() { List = new List<Invoice>() } };

            try
            {
                List<SqlParameter> parameters = new List<SqlParameter>();
                parameters.Add(new SqlParameter("biUserID", request.User.UserID));

                if (request.User.StoreID != request.User.ppjStoreID)
                {
                    parameters.Add(new SqlParameter("biStoreID", request.User.StoreID));
                }

                parameters.Add(new SqlParameter("iPageIndex", request.PageIndex));
                parameters.Add(new SqlParameter("iPageSize", request.PageSize));
                parameters.Add(new SqlParameter("szSortColumn", request.SortColumn));
                parameters.Add(new SqlParameter("szSortDirection", request.SortDirection));
                parameters.Add(new SqlParameter("biResultCount", 0) { Direction = ParameterDirection.Output });

                Statics.AddDebugParameters(parameters);

                var result = new DataSource().ExecuteDataSet("svc.uspGetInvoiceList", parameters);

                Statics.FetchDebugParameters((BaseResponse)response, result);

                if (result.DataSet != null && result.DataSet.Tables.Count > 0)
                {
                    foreach (DataRow row in result.DataSet.Tables[0].Rows)
                    {
                        response.InvoiceList.List.Add(new Invoice()
                        {
                            ID = Convert.ToInt64(row["BillingID"]),
                            BillingPeriodName = row["BillingPeriodName"].ToString(),
                            BillingRate = Convert.ToDecimal(row["BillingRate"]),
                            BillingTypeName = row["BillingTypeName"].ToString(),
                            BillingUnit = Convert.ToInt64(row["BillingUnit"]),
                            DomainName = row["DomainName"].ToString(),
                            StoreID = Convert.ToInt64(row["StoreID"]),
                            StoreName = row["StoreName"].ToString(),
                            BillingDate = Convert.ToDateTime(row["BillingDate"]),
                            From = Convert.ToDateTime(row["DateFrom"]),
                            To = Convert.ToDateTime(row["DateTo"]),
                            NumberOfPeriod = Convert.ToInt32(row["NumberOfPeriod"]),
                            Total = Convert.ToDecimal(row["InvTotal"]),
                            Year = Convert.ToInt64(row["Year"]),
                            Status = row["Status"].ToString()
                        });
                    }

                    response.InvoiceList.ResultCount = Convert.ToInt64(result.Parameters["biResultCount"].Value);
                }

                response.InvoiceList.PageIndex = request.PageIndex;
                response.InvoiceList.PageSize = request.PageSize;
                response.InvoiceList.SortColumn = request.SortColumn;
                response.InvoiceList.SortDirection = request.SortDirection;

                Statics.FetchDebugParameters((BaseResponse)response, result);
            }
            catch (Exception ex)
            {
                response.Exception = ex;
            }

            return response;
        }

        [HttpPost]
        public InvoiceListResponse GetInvoiceDetails(InvoiceRequest request)
        {
            InvoiceListResponse response = new InvoiceListResponse() { InvoiceList = new InvoiceList() { List = new List<Invoice>() } };

            try
            {
                List<SqlParameter> parameters = new List<SqlParameter>();
                parameters.Add(new SqlParameter("biBillingID", request.Invoice.ID));
                parameters.Add(new SqlParameter("biUserID", request.UserID));

                parameters.Add(new SqlParameter("iPageIndex", 1));
                parameters.Add(new SqlParameter("iPageSize", 100000));
                parameters.Add(new SqlParameter("szSortColumn", string.Empty));
                parameters.Add(new SqlParameter("szSortDirection", string.Empty));
                parameters.Add(new SqlParameter("biResultCount", 0) { Direction = ParameterDirection.Output });

                Statics.AddDebugParameters(parameters);

                var result = new DataSource().ExecuteDataSet("svc.uspGetInvoiceDetailsList", parameters);

                Statics.FetchDebugParameters((BaseResponse)response, result);

                if (result.DataSet != null && result.DataSet.Tables.Count > 0)
                {
                    foreach (DataRow row in result.DataSet.Tables[0].Rows)
                    {
                        response.InvoiceList.List.Add(new Invoice()
                        {
                            BillingPeriodName = row["BillingPeriodName"].ToString(),
                            BillingRate = Convert.ToDecimal(row["BillingRate"]),
                            BillingTypeName = row["BillingTypeName"].ToString(),
                            BillingUnit = Convert.ToInt64(row["BillingUnit"]),
                            DomainName = row["DomainName"].ToString(),
                            OrderSubmitFlag = Convert.ToBoolean(row["OrderSubmitFlag"]),
                            PopUpFlag = Convert.ToBoolean(row["PopUpFlag"]),
                            PopUpOrderTotal = Convert.ToDecimal(row["PopUpOrderTotal"]),
                            SessionDate = Convert.ToDateTime(row["SessionDate"]),
                            StoreName = row["StoreName"].ToString(),
                            SubmitOrderTotal = Convert.ToDecimal(row["SubmitOrderTotal"])
                        });
                    }

                    response.InvoiceList.ResultCount = Convert.ToInt64(result.Parameters["biResultCount"].Value);
                }

                Statics.FetchDebugParameters((BaseResponse)response, result);
            }
            catch (Exception ex)
            {
                response.Exception = ex;
            }

            return response;
        }

        [HttpPost]
        public ChargeListResponse GetChargeDetails(InvoiceRequest request)
        {
            ChargeListResponse response = new ChargeListResponse() { ChargeList = new ChargeList() { List = new List<Charge>() } };

            try
            {
                List<SqlParameter> parameters = new List<SqlParameter>();
                parameters.Add(new SqlParameter("biBillingID", request.Invoice.ID));
                parameters.Add(new SqlParameter("biUserID", request.UserID));

                parameters.Add(new SqlParameter("iPageIndex", 1));
                parameters.Add(new SqlParameter("iPageSize", 100000));
                parameters.Add(new SqlParameter("szSortColumn", string.Empty));
                parameters.Add(new SqlParameter("szSortDirection", string.Empty));
                parameters.Add(new SqlParameter("biResultCount", 0) { Direction = ParameterDirection.Output });

                Statics.AddDebugParameters(parameters);

                var result = new DataSource().ExecuteDataSet("svc.uspGetAuthTranDetails", parameters);

                Statics.FetchDebugParameters((BaseResponse)response, result);

                if (result.DataSet != null && result.DataSet.Tables.Count > 0)
                {
                    foreach (DataRow row in result.DataSet.Tables[0].Rows)
                    {
                        response.ChargeList.List.Add(new Charge()
                        {
                            TransactionID = Convert.ToInt64(row["TransactionID"]),
                            Created = Convert.ToDateTime(row["DateCreated"]),
                            Updated = Convert.ToDateTime(row["DateUpdated"]),
                            Number = row["InvoiceNumber"].ToString(),
                            Description = row["InvoiceDescription"].ToString(),
                            Amount = Convert.ToDecimal(row["Amount"]),
                            CustomerProfileID = row["CustomerProfileID"].ToString(),
                            CustomerPaymentProfileID = row["CustomerPaymentProfileID"].ToString(),
                            TransID = row["TransID"].ToString(),
                            TranType = row["TranType"].ToString(),
                            retCode = row["retCode"].ToString(),
                            ErrMsg = row["ErrMsg"].ToString(),
                            CPReturnCode = row["CPReturnCode"].ToString(),
                            CPPReturnCode = row["CPPReturnCode"].ToString(),
                            TranReturnCode = row["TranReturnCode"].ToString()
                        });
                    }

                    response.ChargeList.ResultCount = Convert.ToInt64(result.Parameters["biResultCount"].Value);
                }

                Statics.FetchDebugParameters((BaseResponse)response, result);
            }
            catch (Exception ex)
            {
                response.Exception = ex;
            }

            return response;
        }

        [HttpPost]
        public InvoiceListResponse CreateInvoices(InvoiceListRequest request)
        {
            InvoiceListResponse response = new InvoiceListResponse() { InvoiceList = new InvoiceList() { List = new List<Invoice>() } };

            try
            {
                List<SqlParameter> parameters = new List<SqlParameter>();
                parameters.Add(new SqlParameter("biUserID", request.User.UserID));
                parameters.Add(new SqlParameter("bInvoiceExisted", request.InvoiceExisted));
                parameters.Add(new SqlParameter("bManualMode", true));

                if (request.User.StoreID != request.User.ppjStoreID)
                {
                    parameters.Add(new SqlParameter("biStoreID", request.User.StoreID));
                }

                Statics.AddDebugParameters(parameters);

                var result = new DataSource().ExecuteDataSet("svc.uspCreateInvoices", parameters);

                Statics.FetchDebugParameters((BaseResponse)response, result);

                if (result.DataSet != null && result.DataSet.Tables.Count > 0)
                {
                    foreach (DataRow row in result.DataSet.Tables[0].Rows)
                    {
                        response.InvoiceList.List.Add(new Invoice()
                        {
                            ID = Convert.ToInt64(row["BillingID"]),
                            BillingPeriodName = row["BillingPeriodName"].ToString(),
                            BillingRate = Convert.ToDecimal(row["BillingRate"]),
                            BillingTypeName = row["BillingTypeName"].ToString(),
                            BillingUnit = Convert.ToInt64(row["BillingUnit"]),
                            DomainName = row["DomainName"].ToString(),
                            StoreName = row["StoreName"].ToString(),
                            BillingDate = Convert.ToDateTime(row["BillingDate"]),
                            From = Convert.ToDateTime(row["DateFrom"]),
                            To = Convert.ToDateTime(row["DateTo"]),
                            NumberOfPeriod = Convert.ToInt32(row["NumberOfPeriod"]),
                            Total = Convert.ToDecimal(row["InvTotal"]),
                            Year = Convert.ToInt64(row["Year"])
                        });
                    }
                }

                Statics.FetchDebugParameters((BaseResponse)response, result);
            }
            catch (Exception ex)
            {
                response.Exception = ex;
            }

            return response;
        }

        [HttpPost]
        public SuccessFailResponse VoidInvoice(InvoiceRequest request)
        {
            SuccessFailResponse response = new SuccessFailResponse();

            try
            {
                List<SqlParameter> parameters = new List<SqlParameter>();
                parameters.Add(new SqlParameter("biBillingID", request.Invoice.ID));
                parameters.Add(new SqlParameter("biUserID", request.UserID));

                Statics.AddDebugParameters(parameters);

                var result = new DataSource().Execute("svc.uspVoidInvoice", parameters);

                Statics.FetchDebugParameters((BaseResponse)response, result);

                if (response.ErrorNumber == 0)
                {
                    response.IsSuccessful = true;
                }
            }
            catch (Exception ex)
            {
                response.Exception = ex;
            }

            return response;
        }
    }
}
